package com.inter.controller.newoutside;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.inter.entity.common.DeviceFlowUsage;
import com.inter.entity.interentity.utils.UtilsInterfacesPackage;
import com.inter.entity.newinterentity.suspend.request.RequestSuspendDataFlowOrders;
import com.inter.entity.newinterentity.suspend.request.RequestSuspendDataFlowOrdersData;
import com.inter.entity.newinterentity.suspend.request.RequestSuspendDataFlowOrdersTradeData;
import com.inter.entity.newinterentity.suspend.response.ResponseSuspendDataFlowOrders;
import com.inter.entity.newinterentity.suspend.response.ResponseSuspendDataFlowOrdersData;
import com.inter.entity.newpojo.Constant;
import com.inter.insideinterservice.newservice.TurnToSuspendDataFlowOrdersService;
import com.inter.service.PartnerProductPackageService;
import com.inter.service.PartnerService;
import com.inter.service.SequenceService;
import com.inter.utils.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 暂停流量套餐订单
 * 接入方可以通过调用该接口，对某个设备进行停机操作，关闭其数据流量服务。
 * 停机后的设备，如果在指定的周期内没有复机，那么此设备将被废弃，占用的码号数据将被回收。
 *
 * @author lm
 * @date 2018/12/28
 */
@RestController
@Api(description = "暂停流量套餐订单")
public class SuspendDataFlowOrdersController {

    private static Logger logger = Logger.getLogger(SuspendDataFlowOrdersController.class);

    @Autowired
    private SequenceService sequenceService;
    @Autowired
    PartnerService partnerService;
    @Autowired
    PartnerProductPackageService partnerProductPackageService;

    @CrossOrigin
    @RequestMapping(value = "suspendDataFlowOrders", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "暂停流量套餐订单", response = ResponseSuspendDataFlowOrders.class)
    public String suspendDataFlowOrders(@ApiParam @RequestBody RequestSuspendDataFlowOrders requestSuspendDataFlowOrders) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
        String requestStr = JSON.toJSONString(requestSuspendDataFlowOrders);
        if (StringUtils.isBlank(requestStr)) {
            logger.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            logger.info("前端请求是：" + requestStr);
            RequestSuspendDataFlowOrders requestPackage = JSONArray.parseObject(requestStr, RequestSuspendDataFlowOrders.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                logger.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                logger.info("请求的签名是：" + requestSign);
                RequestSuspendDataFlowOrdersData requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    logger.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String partnerCode = requestData.getPartnerCode();
                    String partnerName = partnerProductPackageService.queryPartnerNameBypartnerCode(partnerCode);
                    String secret = partnerService.findSecretByPartnerCode(partnerCode);
                    logger.info("渠道名称：" + partnerName + ";密钥是：" + secret);
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String tradeTime = requestData.getTradeTime();
                    String token = requestData.getToken();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();

                    RequestSuspendDataFlowOrdersTradeData tradeData = requestData.getTradeData();

                    if (StringUtils.isBlank(partnerCode) || StringUtils.isBlank(partnerName) || StringUtils.isBlank(secret) || StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(tradeTime) ||
                            StringUtils.isBlank(token) || StringUtils.isBlank(tradeType) || StringUtils.isBlank(lang) || tradeData == null) {
                        logger.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        String deviceId = requestData.getTradeData().getDeviceId();
                        String orderId = requestData.getTradeData().getOrderId();

                        if (StringUtils.isBlank(deviceId) || StringUtils.isBlank(orderId)) {
                            logger.info("请求报文不合法:tradeData的值为null或者为空");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {
                            // 将请求体json转成String
                            String str = JSON.toJSONString(requestData);
                            String sign = utils.calculateSignature(str);
                            logger.info("计算的签名是：" + sign);
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                logger.info("签名验证失败！");
                                jsonString = utils.publicMessage(ConnSeqNo, partnerCode, tradeTime, token, tradeType);
                                return jsonString;
                            } else {//签名通过，去北京接口查询

                                TurnToSuspendDataFlowOrdersService suspendDataFlowOrdersService = new TurnToSuspendDataFlowOrdersService();

                                DeviceFlowUsage usage = suspendDataFlowOrdersService.suspendDataFlowOrders(deviceId, orderId, partnerCode, secret);

                                if (usage == null) {
                                    //无返回信息
                                    ResponseSuspendDataFlowOrdersData data = new ResponseSuspendDataFlowOrdersData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setToken(token);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(curtime);
                                    data.setTradeRstCode(1203);
                                    data.setTradeRstMessage("The suspension of the package order for unknown reasons failed;套餐订单未知原因暂停失败！");

                                    ResponseSuspendDataFlowOrders suspend = new ResponseSuspendDataFlowOrders();
                                    suspend.setData(data);
                                    suspend.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                    // 返回给调用者的报文
                                    jsonString = JSON.toJSONString(suspend);
                                    logger.info("响应报文：" + jsonString);
                                    return jsonString;

                                } else {
                                    if (true == Constant.RET_CODE_0000.equalsIgnoreCase(usage.getRetCode())) {
                                        //成功返回的
                                        ResponseSuspendDataFlowOrdersData data = new ResponseSuspendDataFlowOrdersData();
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setToken(token);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(curtime);
                                        data.setTradeRstCode(1000);
                                        data.setTradeRstMessage("success");

                                        ResponseSuspendDataFlowOrders suspend = new ResponseSuspendDataFlowOrders();
                                        suspend.setData(data);
                                        suspend.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                        // 返回给调用者的报文
                                        jsonString = JSON.toJSONString(suspend);
                                        logger.info("响应报文：" + jsonString);
                                        return jsonString;
                                    } else {
                                        //有内容但是不是0000的
                                        ResponseSuspendDataFlowOrdersData data = new ResponseSuspendDataFlowOrdersData();
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setToken(token);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(curtime);
                                        data.setTradeRstCode(Integer.parseInt(usage.getRetCode()));
                                        data.setTradeRstMessage(usage.getResultInfo());

                                        ResponseSuspendDataFlowOrders suspend = new ResponseSuspendDataFlowOrders();
                                        suspend.setData(data);
                                        suspend.setSign(MD5.calcMD5(JSON.toJSONString(data)));
                                        // 返回给调用者的报文
                                        jsonString = JSON.toJSONString(suspend);
                                        logger.info("响应报文：" + jsonString);
                                        return jsonString;

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }


    }


}
